<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<style>
    * {
        margin: 0;
        padding: 0;
    }

    .box {
        width: 50%;
        margin: 20px auto 0;
    }

    .box > div {
        margin-top: 20px;
    }

    .box > div:nth-child(odd) {
        background-color: #fafafa;
    }

    .box .talk-panel p:nth-child(odd) {
        background-color: #f5f5f5;
    }
</style>

<div id="app">

    <div class="box" v-if="able">

        <h1> online chatroom </h1>

        <div>
            输入想要使用的用户名: <input v-model.trim="username">
        </div>

        <div class="status">
            <div>
                <button :disabled="connected" @click="connect">连接</button>
                <button :disabled="!connected" @click="disconnect">断开连接</button>
            </div>
            您的状态：<em :style="'color:' + (connected ? 'green':'red') ">
            {{ connected ? '已连接':'未连接' }}
        </em>
        </div>

        <div>
            <h2>在线用户列表</h2>
            <ul>
                <li v-for="(u,index) in online_users"
                    :key="index"
                    @click="talk_to = u.username">
                    <a href="javascript:;">{{u.username}}</a>
                </li>
            </ul>
        </div>

        <div>
            <h2>发送消息</h2>
            对象: <select v-model="talk_to">
            <option v-for="(u,index) in online_users" :key="index">
                {{ u.username }}
            </option>
        </select> <br/>
            消息：<input v-model="talk_content" placeholder="请输入想发送的内容"> <br/>
            <button @click="sendMessage">发送消息</button>
        </div>

        <div class="talk-panel">
            <h2>聊天消息</h2>
            <p v-for="(item,index) in talk_history" :key="index">
                [{{item.time || timeFormatter}}], [{{item.from}}] 发送给 [{{item.to}}] >>> [{{item.message}}]
            </p>
        </div>

    </div>

</div>

</body>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                username: 'JackChan',
                online_users: [],
                message_list: [],
                able: true, // 浏览器是否支持 ws
                talk_to: undefined,
                talk_content: undefined, // 聊天内容
                connected: false,//是否已连接
                ws_url: "ws://localhost:8888/ws/",   // ws暴露地址
                socket: undefined,
                talk_history: []
                //talk_history: [{time: this.thisTime(), from: 'aaa', to: '我', message: '八嘎呀路'}]
            }
        },
        create() {
            if (typeof (WebSocket) === 'undefined') {
                this.message('您的浏览器不支持 websocket !')
                this.able = false
            }
        },
        mounted() {
            if (!this.able) alert('您的浏览器不支持 WebSocket')
        },
        methods: {
            connect() {
                if (!this.username || this.username === '') {
                    alert('请输入名字')
                    return
                }
                if (this.connected) {
                    alert('已连接')
                    return
                }
                // 如果开启则关闭
                if (this.socket) {
                    this.socket.close()
                    this.socket = null
                }
                // 初始化
                this.talk_to = undefined
                this.talk_content = undefined
                this.talk_history = []
                this.online_users = []
                // 建立连接，编写回调
                let ws_url = this.ws_url + this.username
                let that = this
                this.socket = new WebSocket(ws_url)
                this.socket.onopen = function () {
                    that.connected = true
                }
                this.socket.onmessage = function (msg) {
                    console.log('收到消息，', msg)
                    let data = JSON.parse(msg.data)
                    // 判断拿到的消息类型。更新UI
                    if (!data) return
                    // 从server拿到的消息，拆包，共三种消息类型。做的简单
                    if (data.users) {   // 用户列表
                        that.online_users =
                            data.users.filter(u => u.username !== that.username)
                    } else if (data.from) {    // 聊天信息
                        //console.log('聊天信息')
                        that.talk_history.push({time: that.thisTime(), from: data.from, to: 'Me', message: data.text})
                    } else if (data.msg) {      // 连接失败消息
                        alert(data.msg)
                    }
                }
                this.socket.onerror = function () {
                    alert('onerror, ws 发生了错误')
                }
                this.socket.onclose = function () {
                    console.log('连接已关闭')
                    that.connected = false
                    that.online_users = []
                    that.talk_history = []
                    that.talk_to = undefined
                    that.talk_content = undefined
                }
            },
            disconnect() {
                console.log('disconnect')
                if (!this.connected) {
                    alert('已关闭')
                }
                if (this.socket) {
                    this.socket.close()
                }
                this.socket = null
            },
            thisTime() {
                const now = new Date()
                return now.getDate() + "/" + (now.getMonth() + 1) + "/" + now.getFullYear() + " " +
                    now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds()
            },
            sendMessage() {
                if (!this.connected || !this.socket) {
                    alert('请先登录')
                    return
                }
                if (!this.talk_to) {
                    alert('请选择聊天对象')
                    return
                }
                if (!this.talk_content || this.talk_content === '') {
                    alert('请输入聊天内容')
                    return
                }
                console.log('talk_to = ', this.talk_to, ', msg = ', this.talk_content)
                this.socket.send(JSON.stringify({from: this.username, to: this.talk_to, text: this.talk_content}))
                this.talk_history.push({time: this.thisTime(), from: '我', to: this.talk_to, message: this.talk_content})
            }
        }
    })
</script>
</html>